// mircoApp/gradevin/purchasingCenter/purchasingCenter.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    keyword: "",
    show: false,
    info: [],
    carts: [],
    // 购物车数量
    cartNum: 0,
    // 总价
    countPirce: 0,

    // 规格弹窗 start
    popupSpecs: false,
    goodsInfo: [],
    carts: [],
    // 规格弹窗 end

    page: 1,
    isLoadMore: false,
    total_page: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.init();
    this.getData();
    this.getCart();
  },
  init() {
    this.setData({
      page: 1,
      info: [],
      isLoadMore: true,
      total_page: 0,
      show: false,
      keyword: "",
      carts: [],
    });
  },
  // 规格弹窗 start
  closePopup() {
    this.setData({
      popupSpecs: false,
    });
  },
  submitAction_add(e) {
    let {
      goods_id,
      option_id
    } = e.detail;
    this.addPost({
      id: goods_id
    }, option_id);
  },
  cartChange(e) {
    let {
      id,
      num
    } = e.detail;
    console.log(id, num);
    if (num == 0) {
      this.destroyCartPost(id);
    } else {
      this.cartTotalChange(id, num);
    }
  },
  // 规格弹窗 end
  toGoodDetail(e) {
    let {
      id
    } = e.currentTarget.dataset.item;
    console.log(e)
    // 去详情
    wx.navigateTo({
      url: `/packageA/detail_v2/detail_v2?id=${id}&purchasing=Center`,
    })
  },
  toBuy() {
    let cartId = [];
    for (let i = 0; i < this.data.carts.length; i++) {
      // cartId.push(String(this.data.carts[i].id));
      cartId.push(this.data.carts[i].id);
    }
    let urls = `/packageD/buy/myOrder_v2/myOrder_v2?tag=purchasingCenter&cart_ids=${JSON.stringify(cartId)}`;
    console.log(cartId, "购物车id", urls);
    // tag=-1&cart_ids=[857,858]
    wx.navigateTo({
      url: urls,
    })
    // 去下单
  },
  inpBlur(e) {
    let val = e.detail.value;
    let item = e.currentTarget.dataset.item;
    console.log(val, e);
    if (val == item.total) return
    if (val == 0 || !e.detail.value) {
      this.destroyCartPost(item.id);
      return
    }
    this.cartTotalChange(item.id, val)
  },
  showOpen() {
    this.setData({
      show: true,
    });
  },
  tapClose() {
    this.setData({
      show: false,
    });
  },
  addPost(item, optionsId) {
    console.log(item, "dddddddddddddddddd");
    let json = {
      goods_id: item.id,
      total: 1,
    };
    if (optionsId) {
      json.option_id = optionsId;
    }
    let urlStr = app.getNetAddresss(
      "plugin.gradevin-stock.frontend.controllers.member-cart.store"
    );
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          app.tips(res.msg);
          this.getCart();
        } else {
          app.tips(res.msg);
        }
      },
    });
  },
  addCart(e) {
    let {
      item
    } = e.currentTarget.dataset;
    console.log(item, "ddddddddddd");
    if (item.has_option == 1) {
      this.setData({
        popupSpecs: true,
        goodsInfo: item,
      });
      console.log(this.data.goodsInfo);
      return;
    }
    this.addPost(item);
  },
  addPlus(e) {
    let {
      item
    } = e.currentTarget.dataset;
    let total = item.total + 1;
    this.cartTotalChange(item.id, total);
  },
  minusPost(e) {
    let {
      item
    } = e.currentTarget.dataset;
    let total = item.total - 1;
    if (total == 0) {
      this.destroyCartPost(item.id);
      return;
    }
    this.cartTotalChange(item.id, total);
  },
  destroyCart() {
    let cartId = [];
    for (let i = 0; i < this.data.carts.length; i++) {
      cartId.push(String(this.data.carts[i].id));
    }
    cartId = cartId.toString();
    this.destroyCartPost(cartId);
  },
  destroyCartPost(cartId) {
    let urlStr = app.getNetAddresss(
      "plugin.gradevin-stock.frontend.controllers.member-cart.destroy"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        ids: cartId,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          app.tips(res.msg);
          this.setData({
            show: false,
          });
          this.getCart();
        } else {
          app.tips(res.msg);
        }
      },
    });
  },
  cartTotalChange(cartid, total) {
    let urlStr = app.getNetAddresss(
      "plugin.gradevin-stock.frontend.controllers.member-cart.updateNumV2"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        id: cartid,
        num: total,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          app.tips(res.msg);
          this.getCart();
        } else {
          app.tips(res.msg);
        }
      },
    });
  },
  getData() {
    let urlStr = app.getNetAddresss(
      "plugin.gradevin-stock.frontend.controllers.index.purchase-of-center"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        keyword: this.data.keyword,
        page: this.data.page,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            info: res.data.list.data,
          });
        } else {
          app.tips(res.msg);
        }
      },
    });
  },
  getMoreData() {
    let urlStr = "";
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      wx.showLoading({
        title: "正在加载",
      });
      this.setData({
        page: this.data.page + 1,
      });
      urlStr = app.getNetAddresss(
        "plugin.gradevin-stock.frontend.controllers.index.purchase-of-center"
      );
      app._postNetWork({
        url: urlStr,
        data: {
          keyword: this.data.keyword,
          page: this.data.page,
        },
        success: (resdata) => {
          wx.hideLoading();
          let res = resdata.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              info: this.data.info.concat(res.data.list.data),
            });
          } else {
            this.data.page = this.data.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          console.log(res);
        },
      });
    }
  },
  getCart() {
    let urlStr = app.getNetAddresss(
      "plugin.gradevin-stock.frontend.controllers.member-cart.index"
    );
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            carts: res.data,
          });
          let total = 0;
          let countPirce = 0;
          for (let i = 0; i < this.data.carts.length; i++) {
            if (this.data.carts[i].is_failure != 1) {
              total += this.data.carts[i].total;
              countPirce += Number(this.data.carts[i].goods.price) * this.data.carts[i].total;
            }
          }
          // countPirce = countPirce * total;
          this.setData({
            cartNum: total,
            countPirce: countPirce.toFixed(2),
          });
        } else {
          app.tips(res.msg);
        }
      },
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log("没有更多了");
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});